from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
import cryptography, base64,requests,json,uuid,datetime
from base64 import b64encode
from decimal import Decimal
from db.models import InvoiceItem,BatchAssignCode,LeqLastFpNum,LeqOnlyOneFp,InvoiceLimit,Invoice
from django.db.models.aggregates import Sum
from utils.dateOpr import tomorrow
from django.core.serializers.json import DjangoJSONEncoder
http_status_codes = {
    200: "成功",
    500: "请求云服务集成平台异常 | 服务接入异常，请联系管理员",
    5001: "云服务集成平台响应异常",
    40322: "直连单位无资格",
    40321: "使用单位无资格",
    4055: "通过平台序号未查询到此使用单位信息",
    4054: "通过平台序号未查询到此直连单位信息",
    4047: "未查询到该单位的测试批次号",
    4049: "未查询到该能力与对应服务的相关信息",
    4032: "使用单位无授权服务",
    4033: "使用单位未授权此服务",
    4056: "云服务APP未找到",
    4057: "报文解密失败",
    -1: "未知错误"
}
blueorred_codes = {
    1:'0',
    2:'1'
}
INFO_KIND_INDEX = {
    61:'01',
    62:'02',
    '61':'01',
    '62':'02'
}
# 解密方法
def sm4_decrypt(Key, request):
    Key = bytes(Key, encoding='utf-8')
    backend = default_backend()

    # 将Base64编码的密文解码为二进制数据
    request = base64.b64decode(request)

    # 创建解密器对象
    cipher = Cipher(algorithms.SM4(Key), modes.ECB(), backend=backend)
    decryptor = cipher.decryptor()

    # 进行解密操作
    plaintext = decryptor.update(request) + decryptor.finalize()

    # 去除填充数据
    unpadder = padding.PKCS7(128).unpadder()
    plaintext = unpadder.update(plaintext) + unpadder.finalize()

    return plaintext.decode('utf-8')

#32位唯一数字串
def generate_unique_32bit_number():
    uuid_bytes = uuid.uuid4().bytes
    unique_32bit_number = int.from_bytes(uuid_bytes, byteorder='big')
    return unique_32bit_number


# 加密方法
def encrypt_file(data, Key):
    # 创建SM4算法的Cipher对象
    Key = bytes(Key, encoding='utf-8')
    cipher = Cipher(algorithms.SM4(Key), modes.ECB(), backend=default_backend())

    # 创建加密器
    encryptor = cipher.encryptor()
    data = json.dumps(data,cls=DjangoJSONEncoder)
    # 对明文进行填充
    padder = cryptography.hazmat.primitives.padding.PKCS7(128).padder()
    padded_plaintext = padder.update(data) + padder.finalize()

    # 加密明文
    ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()

    # 使用Base64编码输出加密结果
    encoded_ciphertext = b64encode(ciphertext)
    # parsed_data = json.loads(decoded_data)
    # 返回加密后的字符串
    return encoded_ciphertext.decode('utf-8')

# 调用乐企接口
def call_leq_api(saleInvoiceConfig,data,serviceCode,sxcsbz=False,ylbm=None,nlbm='911001'):
    if nlbm == 'no':
        nlbm = ''
    else:
        nlbm = '''/%s/''' %nlbm
    
    url = """%s/911001/%s""" %(saleInvoiceConfig.leq_url,serviceCode)
    data = encrypt_file(data, saleInvoiceConfig.leq_smKey)
    
    headers = {
        'Content-Type': 'application/json',
        'jrdwptbh':saleInvoiceConfig.leq_jrdwptbh,
        'sydwptbh':saleInvoiceConfig.leq_sydwptbh,
    }
    if sxcsbz:
        headers['sxcsbz'] = '1'
    if ylbm:
        headers['ylbm'] = ylbm
    response = requests.post(url, headers=headers, data=data)
    print(response.content)
    if response.status_code == 200:
        response_data = response.json()
        if response_data.get('httpStatusCode') == 200:
            body = response_data.get('body')
            if not body:
                return {
                    'returnCode':'9999',
                    'returnMessage':'乐企返回数据为空',
                }
            
            if not body:
                return {
                    'returnCode':'9999',
                    'returnMessage':'乐企返回数据为空',
                }
            res = body.get('Response')
            
            if not res:
                return {
                    'returnCode':'9999',
                    'returnMessage':'乐企返回数据为空',
                }
            if res.get('Error'):
                return {
                    'returnCode':body.get('Error').get('Code'),
                   'returnMessage':body.get('Error').get('Message'),
                }
            Data = res.get('Data')
            if not Data:
                return {
                    'returnCode':'9999',
                    'returnMessage':'乐企返回数据为空',
                }
            try:
                result = sm4_decrypt(saleInvoiceConfig.leq_smKey, Data)
                return json.loads(result)
            except Exception as e:
                return {
                    'returnCode':'9999',
                    'returnMessage':f'解密失败,{e}',
                }
        return result
    else:
        return {
            'returnCode':'9999',
            'returnMessage':f'{response.status_code},网络错误',
        }
    
#获取 数电票 批量预赋码信息
def get_ydptbzxx(saleInvoiceConfig,sxcsbz=False,ylbm=None):
    data = {
        "nsrsbh": saleInvoiceConfig.NSRSBH,
        "lysl": "5000",
        "ywlsh": "%s%s%s" %(saleInvoiceConfig.leq_jrdwptbh,saleInvoiceConfig.leq_sydwptbh,generate_unique_32bit_number())
    }
    return call_leq_api(saleInvoiceConfig,data,'QDFPPLFM',sxcsbz,ylbm)

#查询 发票额度
def query_fpelx(saleInvoiceConfig,sxcsbz=False,ylbm=None):
    data = {
        "nsrsbh": saleInvoiceConfig.NSRSBH,
    }
    return call_leq_api(saleInvoiceConfig,data,'CXSXED',sxcsbz,ylbm)

#下载/退回 发票额度
def download_fpelx(saleInvoiceConfig,sqed=None,sqlx=0,sxcsbz=False,ylbm=None):
    data = {
        "nsrsbh": saleInvoiceConfig.NSRSBH,
        "ptbh": saleInvoiceConfig.leq_ptbh,
        "sqlx": '%s' %sqlx,
        "sqed": sqed,
        "ywlsh": "%s%s%s" %(saleInvoiceConfig.leq_jrdwptbh,saleInvoiceConfig.leq_sydwptbh,generate_unique_32bit_number())
    }
    res = call_leq_api(saleInvoiceConfig,data,'XZTHSXED',sxcsbz,ylbm)
    if res.get('returncode') == '00':
        InvoiceLimit.objects.create(
            app=saleInvoiceConfig.app,
            saleInvoiceConfig = saleInvoiceConfig,
            NSRSBH=saleInvoiceConfig.NSRSBH,
            syqjq= datetime.datetime.strptime(res.get('syqjq'), '%Y%m%d'),
            syqjz= datetime.datetime.strptime(res.get('syjqq'), '%Y%m%d'),
            limit_amount = sqed if sqlx==0 else -sqed,
        )
        return {
            'syqjq':res.get(u'syqjq'),
            'syqjz':res.get(u'syqjz'),
            'sqed':sqed
        }
    else:
        return {
            'returnCode':res.get('returncode'),
           'returnMessage':res.get('returnmsg')
        }
    
    
#查询纳税人风险信息
def query_nsrsfxx(saleInvoiceConfig,sxcsbz=False,ylbm=None):
    data = {
        "nsrsbh": saleInvoiceConfig.NSRSBH,
    }
    return call_leq_api(saleInvoiceConfig,data,'CXNSRFXXX',sxcsbz,ylbm)

#查询纳税人基本信息
def query_nsrsxx(saleInvoiceConfig,sxcsbz=False,ylbm=None):
    data = {
        "nsrsbh": saleInvoiceConfig.NSRSBH,
    }
    return call_leq_api(saleInvoiceConfig,data,'CXNSRJBXX',sxcsbz,ylbm)

#查询可用税率信息
def query_syslxx(saleInvoiceConfig,sxcsbz=False,ylbm=None):
    data = {}
    return call_leq_api(saleInvoiceConfig,data,'CXKYSL',sxcsbz,ylbm)

#查询税收分类编码信息
def query_txscdmxx(saleInvoiceConfig,sxcsbz=False,ylbm=None):
    data = {
        'nsrsbh': saleInvoiceConfig.NSRSBH,
        'sjc':datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
        'sjswjgdm':saleInvoiceConfig.leq_ssjswjgdm,
    }
    return call_leq_api(saleInvoiceConfig,data,'CXSSFLBM',sxcsbz,ylbm)

#查询数电红字确认单明细信息
def query_ydhcdmx(saleInvoiceConfig,kpsq,sxcsbz=False,ylbm=None):
    data = {
        'uuid' : kpsq.redinv_uuid,
        "xsfnsrsbh": kpsq.GHF_NSRSBH,    
    }
    return call_leq_api(saleInvoiceConfig,data,'CXQDHZQRDMX',sxcsbz,ylbm)

#数电票上传
def upload_ydpt(saleInvoiceConfig,kpsq,sxcsbz=False,ylbm=None):
    data = []
    
    kpsqGoodss = InvoiceItem.objects.filter(invoice=kpsq)
    fpmxList = []
    for kpsqGood in kpsqGoodss:
        fpmxList.append({
            "mxxh": kpsqGood.xh,
            "dylzfpmxxh": kpsqGood.yp_xh if kpsqGood.yp_xh else None,
            "hwhyslwfwmc": "%s%s" %(kpsqGood.spfwjc,kpsqGood.XMMC),
            "spfwjc": kpsqGood.spfwjc,
            "xmmc": kpsqGood.XMMC,
            "ggxh": kpsqGood.GGXH if kpsqGood.GGXH else "",
            "dw": kpsqGood.XMDW if kpsqGood.XMDW else "",
            "sl": kpsqGood.XMSL if kpsqGood.XMSL else "",
            "dj": kpsqGood.XMDJ,
            "je": kpsqGood.XMJE,
            "slv": kpsqGood.SL,
            "se": kpsqGood.SE,
            "hsje": kpsqGood.XMJE+kpsqGood.SE,
            #"kce": "扣除额",#未实现
            "sphfwssflhbbm": kpsqGood.SPBM,
            "fphxz": kpsqGood.FPHXZ.zfill(2),
            "yhzcbs": kpsqGood.ZZSTSGL
        })
    item ={
        {
        "fphm": '%s' %kpsq.FP_HM,
        "lzfpbz": blueorred_codes.get(kpsq.KPLX),
        "ptbh": saleInvoiceConfig.leq_ptbh,
        "fppz": INFO_KIND_INDEX.get(kpsq.InfoKind),
        "gmfzrrbz": kpsq.gmfzrrbz if kpsq.gmfzrrbz else "N",
        "tdys": kpsq.tdyslxdm if kpsq.tdyslxdm else "",
        "qyDm": saleInvoiceConfig.leq_qydm,
        #"cezslxDm": "差额征税类型代码",
        #"sgfplxDm": "收购发票类型代码",
        #"ckywsyzcDm": "出口业务适用政策代码",
        #"zzsjzjtDm": "增值税即征即退代码",
        "xsfnsrsbh": kpsq.XHF_NSRSBH,
        "xsfmc": kpsq.XHFMC,
        "xsfdz": kpsq.XHF_DZ,
        "xsfdh": kpsq.XHF_DH,
        "xsfkhh": kpsq.XHF_YHMC,
        "xsfzh": kpsq.XHF_YHZH,
        "gmfnsrsbh": kpsq.GHF_NSRSBH,
        "gmfmc": kpsq.GHFMC,
        "gmfdz": kpsq.GHF_DZ,
        "gmfdh": kpsq.GHF_SJ,
        "gmfkhh": kpsq.GHF_YHMC,
        "gmfzh": kpsq.GHF_YHZH,
        #"gmfjbr": "经办人",
        #"jbrsfzjhm": "经办人身份证件号码",
        #"gmfjbrlxdh": "经办人联系电话",
        "hjje": kpsq.HJBHSJE,
        "hjse": kpsq.HJSE,
        "jshj": kpsq.KPHJJE,
        #"skyhmc": "收款银行名称",
        #"skyhzh": "收款银行账号",
        #"jsfs": "结算方式",
        #"ysxwfsd": "应税行为发生地",
        "kpr": kpsq.KPR,
        #"kprzjhm": "开票人证件号码",
        #"kprzjlx": "开票人证件类型",
        "dylzfphm": kpsq.YFP_DM,
        "hzqrxxdbh": kpsq.YFP_HM,
        "hzqrduuid": kpsq.redinv_uuid,
        "bz": kpsq.BZ,
        "ip": saleInvoiceConfig.leq_ip,
        "macdz": saleInvoiceConfig.leq_mac,
        #"cpuid": "CPU序列号",
        #"zbxlh": "主板序列号",
        "kprq": kpsq.KPRQ.strftime('%Y-%m-%d %H:%M:%S'),
        "sfzsxsfyhzhbq": "N",
        "sfzsgmfyhzhbq": "N",
        #"skrxm": "收款人姓名",
        #"fhrxm": "复核人姓名",
        "fpmxList": fpmxList
        }
    }
    data.append(item)
    res = call_leq_api(saleInvoiceConfig,json.dumps(data),'QDFPSC',sxcsbz,ylbm)
    if res.get('returncode') == '00':
        kpsq.FPQQLSH = res.get('sllsh')
        kpsq.save()
        return {
            'returnCode':'0000',
            'returnMessage':res.get('returnmsg'),
        }
    else:
        return {
            'returnCode':res.get('returncode'),
            'returnMessage':res.get('returnmsg')
        }

#查询数电票上传结果
def query_ydpt_upload_result(saleInvoiceConfig,kpsq,sxcsbz=False,ylbm=None):
    data = {
        "sllsh": kpsq.FPQQLSH
    }
    res = call_leq_api(saleInvoiceConfig,data,'CXQDFPSCJG',sxcsbz,ylbm)
    if res.get('returncode') == '00':
        if res.get('resultList')[0].get('status') in ['00','03']:
            return {
                'returnCode':'0000',
                'returnMessage':res.get('returnmsg'),
                'FP_HM':res.get('resultList')[0].get('fphm'),
                'KPRQ':kpsq.KPRQ.strftime('%Y-%m-%d %H:%M:%S'),
                'FP_DM':"",
                'PDF_URL':"",
                'FWM':"",
            }
        elif res.get('resultList')[0].get('status') == '01':
            return {
                'returnCode':'9411',
                'returnMessage':res.get('resultList')[0].get('message'),
            }
        elif res.get('resultList')[0].get('status') == '02':
            return {
                'returnCode':'9998',
                'returnMessage':res.get('resultList')[0].get('message'),
            }
        else:
            return {
                'returnCode':'9999',
                'returnMessage':'乐企业未知错误',
            }
    else:
        return {
            'returnCode':'9401',
            'returnMessage':res.get('returnmsg')
        }
    
#数电红字确认单申请
def apply_ydhcd(saleInvoiceConfig,kpsq,sxcsbz=False,ylbm=None):
    hzqrdmxList = []
    kpsqGoodss = InvoiceItem.objects.filter(invoice=kpsq)
    for kpsqGood in kpsqGoodss:
        hzqrdmxList.append({
            "lzmxxh": kpsqGood.yp_xh,
            "xh": kpsqGood.xh,
            "sphfwssflhbbm": kpsqGood.SPBM,
            "hwhyslwfwmc": '%s%s' %(kpsqGood.spfwjc,kpsqGood.XMMC),
            "spfwjc": kpsqGood.spfwjc,
            "xmmc": kpsqGood.XMMC,
            "ggxh": kpsqGood.GGXH if kpsqGood.GGXH else "",
            "dw": kpsqGood.XMDW if kpsqGood.XMDW else "",
            "fpspdj": kpsqGood.XMDJ,
            "fpspsl": kpsqGood.XMSL if kpsqGood.XMSL else "",
            "je": kpsqGood.XMJE,
            "sl1":kpsqGood.SL,
            "se": kpsqGood.SE,
        })
    data = {
        "lrfsf": "0",
        "xsfnsrsbh": kpsq.XHF_NSRSBH,
        "xsfmc": kpsq.XHFMC,
        "gmfnsrsbh": kpsq.GHF_NSRSBH,
        "gmfmc": kpsq.GHFMC,
        "lzfpdm": kpsq.YFP_DM if kpsq.YFP_DM else "",
        "lzfphm": kpsq.YFP_HM if kpsq.YFP_HM else "",
        "sfzzfpbz": "N",
        "lzkprq": kpsq.YFP_KPRQ.strftime('%Y-%m-%d %H:%M:%S'),
        "lzhjje": -kpsq.HJBHSJE,
        "lzhjse": -kpsq.HJSE,
        "lzfppzDm": INFO_KIND_INDEX.get(kpsq.InfoKind),
        "lzfpTdyslxDm": kpsq.tdyslxdm if kpsq.tdyslxdm else "",
        "hzcxje": -kpsq.HJBHSJE,
        "hzcxse": -kpsq.HJSE,
        "chyyDm": "01",
        "hzqrdmxList": hzqrdmxList,
    }
    res = call_leq_api(saleInvoiceConfig,data,'QDHZQRDSQ',sxcsbz,ylbm)
    if res.get('returncode') == '00':
        kpsq.redinv_uuid = res.get('uuid')
        kpsq.getredinv_statusmc = res.get('hzqrxxztDm')
        kpsq.save()
        return {
            'returnCode':'0000',
            'returnMessage':res.get('returnmsg'),
            'uuid':res.get('uuid'),
        }
    else:
        return {
            'returnCode':res.get('returncode'),
            'returnMessage':res.get('returnmsg')
        }
    
#查询红字确认单申请结果
def query_ydhcd_apply_result(saleInvoiceConfig,kpsq,sxcsbz=False,ylbm=None):
    data = {
        "uuid": kpsq.redinv_uuid,
        "xsfnsrsbh": kpsq.XHF_NSRSBH,
    }
    res = call_leq_api(saleInvoiceConfig,data,'CXQDHZQRDMX',sxcsbz,ylbm)
    if res.get('returncode') == '00':
        if res.get('status') == '00':
            kpsq.getredinv_statusmc = res.get('hzqrxxztDm')
            kpsq.save()
            return {
                'returnCode':kpsq.getredinv_statusmc,
                'returnMessage':res.get('returnmsg'),
            }
    else:
        return {
            'returnCode':'9401',
            'returnMessage':res.get('returnmsg')
        }
    
#初始化预赋码信息
def init_ydptbzxx(saleInvoiceConfig):
    batchAssignCode = BatchAssignCode.objects.filter(saleInvoiceConfig=saleInvoiceConfig).first()
    if not batchAssignCode:
        res = get_ydptbzxx(saleInvoiceConfig)
        if res.get('returncode') == '00':
            batchAssignCode = BatchAssignCode.objects.create(
                app = saleInvoiceConfig.app,
                saleInvoiceConfig = saleInvoiceConfig,
                nsrsbh = saleInvoiceConfig.NSRSBH,
                get_datatime = datetime.datetime.now(),
                fpqshm = res.get('fpqshm'),
                fpzzhm = res.get('fpzzhm'),
            )
            LeqLastFpNum.objects.create(
                app = saleInvoiceConfig.app,
                saleInvoiceConfig = saleInvoiceConfig,
                nsrsbh = saleInvoiceConfig.NSRSBH,
                last_fp_num = int(batchAssignCode.fpqshm),
                max_fp_num = int(batchAssignCode.fpqshm),
            )

    
#发票开具
def fpkjInterface(saleInvoiceConfig,kpsq,sxcsbz=False,ylbm=None):
    if kpsq.KPLX in ['2',2]:
        if not kpsq.redinv_uuid:
            res = apply_ydhcd(saleInvoiceConfig,kpsq,sxcsbz,ylbm)
            if res.get('returnCode') != '0000':
                return {
                    'returnCode':'9999',
                   'returnMessage':'红字确认申请失败%s' %res.get('returnMessage')
                }

        if kpsq.getredinv_statusmc in ['02','03']:
            res = query_ydhcd_apply_result(saleInvoiceConfig,kpsq,sxcsbz,ylbm)
            if res.get('returnCode') not in ['01','04']:
                return {
                    'returnCode':'9401',        
                    'returnMessage':'红字确认单申请确认中',
                }
            if res.get('returnCode') in ['05','06','07','08']:
                kpsq.status = 3
                kpsq.fail_reason = "红字确认单被拒绝拒绝编号：%s 拒绝状态编号：%s" % (kpsq.redinv_uuid,kpsq.getredinv_statusmc)
                kpsq.save()
                return {
                    'returnCode':'9999',        
                    'returnMessage':'红字确认单已拒绝',
                }
        if kpsq.getredinv_statusmc in ['05','06','07','08']:
            kpsq.status = 3
            kpsq.fail_reason = "红字确认单被拒绝拒绝编号：%s 拒绝状态编号：%s" % (kpsq.redinv_uuid,kpsq.getredinv_statusmc)
            kpsq.save()
            return {
                'returnCode':'9999',        
                'returnMessage':'红字确认单已拒绝',
            }
    if not kpsq.FP_HM:
        leqOnlyOneFp = LeqOnlyOneFp.objects.select_for_update().filter(saleInvoiceConfig=saleInvoiceConfig).first()
        if not leqOnlyOneFp:
            leqOnlyOneFp = LeqOnlyOneFp.objects.create(
                app = saleInvoiceConfig.app,
                saleInvoiceConfig = saleInvoiceConfig,
                nsrsbh = saleInvoiceConfig.NSRSBH,
                count = 0,
            )
            leqOnlyOneFp = LeqOnlyOneFp.objects.select_for_update().filter(saleInvoiceConfig=saleInvoiceConfig).first()
        invoiceLimits = InvoiceLimit.objects.filter(app=saleInvoiceConfig,
                                                    syqjq__lte=kpsq.KPRQ,
                                                    syqjz__gt=tomorrow(kpsq.KPRQ.strftime('%Y-%m-%d')))
        #print(invoiceLimits.query.sql_with_params())
        if not invoiceLimits:
            leqOnlyOneFp.save()
            return {
                'returnCode':'9999',        
                'returnMessage':'当前时间段无发票额度',
            }
        sum_invoiceLimit = Decimal(0)
        min_syqjq = None
        max_syqjz = None
        for invoiceLimit in invoiceLimits:
            sum_invoiceLimit += invoiceLimit.limit_amount
            if not min_syqjq or invoiceLimit.syqjq < min_syqjq:
                min_syqjq = invoiceLimit.syqjq
            if not max_syqjz or invoiceLimit.syqjz > max_syqjz:
                max_syqjz = invoiceLimit.syqjz
        sum_invoice_amount = Invoice.objects.filter(saleInvoiceConfig=saleInvoiceConfig,
                                                    KPRQ__gte=min_syqjq,
                                                    KPRQ__lte=max_syqjz,FP_HM__isnull=False).aggregate(Sum('HJBHSJE'))
        if not sum_invoice_amount['HJBHSJE__sum']:
            sum_invoice_amount['HJBHSJE__sum'] = Decimal(0)
        if sum_invoice_amount['HJBHSJE__sum'] + kpsq.HJBHSJE > sum_invoiceLimit:
            leqOnlyOneFp.save()
            return {
                'returnCode':'9999',        
                'returnMessage':'当前时间段发票额度不足',
            }   
        lastFpNum = LeqLastFpNum.objects.select_for_update().filter(saleInvoiceConfig=saleInvoiceConfig,is_useup=False).first()
        if not lastFpNum:
            init_ydptbzxx(saleInvoiceConfig)
            lastFpNum = LeqLastFpNum.objects.select_for_update().filter(saleInvoiceConfig=saleInvoiceConfig,is_useup=False).first()
        if lastFpNum.last_fp_num >= lastFpNum.max_fp_num:
            lastFpNum.is_useup = True
            lastFpNum.save()
            init_ydptbzxx(saleInvoiceConfig)
            lastFpNum = LeqLastFpNum.objects.select_for_update().filter(saleInvoiceConfig=saleInvoiceConfig,is_useup=False).first()
        
        kpsq.KPRQ = datetime.datetime.now()
        
        fpqshm = (lastFpNum.last_fp_num + 1).zfill(20)
        lastFpNum.last_fp_num = lastFpNum.last_fp_num + 1
        kpsq.FP_HM = fpqshm
        kpsq.save()
        lastFpNum.save()
        leqOnlyOneFp.count = leqOnlyOneFp.count + 1
        leqOnlyOneFp.save()
    
    res = upload_ydpt(saleInvoiceConfig,kpsq,sxcsbz,ylbm)
    if res.get('returnCode') == '0000':
        kpsq.status = 1
        kpsq.save()
        return {
            'returnCode':'0000',
            'returnMessage':res.get('returnMessage'),
            'fpqshm':kpsq.FP_HM,
        }
    else:
        kpsq.status = 3
        kpsq.fail_reason = "[%s]%s" %(res.get('returnCode'),res.get('returnMessage'))
        kpsq.save()
        return {
            'returnCode':res.get('returnCode'),
            'returnMessage':res.get('returnMessage'),
        }
    
#开票结果查询
def fpcxInterface(saleInvoiceConfig,kpsq,sxcsbz=False,ylbm=None):
    res = query_ydpt_upload_result(saleInvoiceConfig,kpsq,sxcsbz,ylbm)
    return res

#虚拟单位企业数据查询
def virtual_enterprise_query(saleInvoiceConfig,sxcsbz=False,ylbm=None):
    data = {
        "nsrsbh": saleInvoiceConfig.NSRSBH,
        "ssjswjgDm":saleInvoiceConfig.leq_ssjswjgdm
    }
    return call_leq_api(saleInvoiceConfig,data,'LQSX_SWZJ_GT4_CXXNQYXX',sxcsbz,ylbm,nlbm='no')

#企业基础信息更新
def enterprise_base_info_update(saleInvoiceConfig,data,sxcsbz=False,ylbm=None):
    return call_leq_api(saleInvoiceConfig,data,'LQSX_SWZJ_GT4_GXQYXX',sxcsbz,ylbm,nlbm='no')

#企业信息重置
def enterprise_info_reset(saleInvoiceConfig,sxcsbz=False,ylbm=None):
    data = {
        "nsrsbh": saleInvoiceConfig.NSRSBH,
        "ssjswjgDm":saleInvoiceConfig.leq_ssjswjgdm
    }
    return call_leq_api(saleInvoiceConfig,data,'LQSX_SWZJ_GT4_CZQYXX',sxcsbz,ylbm,nlbm='no')

#企业信息初始化
def enterprise_info_init(saleInvoiceConfig,sxcsbz=False,ylbm=None):
    data = {
        "nsrsbh": saleInvoiceConfig.NSRSBH,
        "ssjswjgDm":saleInvoiceConfig.leq_ssjswjgdm
    }
    return call_leq_api(saleInvoiceConfig,data,'LQSX_SWZJ_GT4_QYXXCSH',sxcsbz,ylbm,nlbm='no')



